// stock/receive_send_detail/receive_send_detail.js
let listBehavior = require('../../behavior/list');

let { formatDate, getMonthFirstDate, getMonthLastDate, } = wx.$util,
  first = formatDate(getMonthFirstDate(), 'yyyy-MM-dd'),
  last = formatDate(getMonthLastDate(), 'yyyy-MM-dd');

Page({
  behaviors: [ listBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {

    list: [],

    //搜索商品
    keyList: [
      {field_id: 'goods_id',field_name: '商品编码'},
      {field_id: 'goods_name',field_name: '商品名称'}
    ],
    //快速搜索
    searchList: [
      {field_id: 'date',type: 'date',field_name: '单据日期',start: first, end: last,},
      {field_id: 'quote_Warehouse',type: 'reference1',mainEntity: 'Warehouse',showFields: 'warehouse_name',field_name: '仓库',optionList: [],optionName: 'warehouse_name',optionId: 'row_id'},
      {field_id: 'table_id',type: 'reference1',field_name: '业务类型',
        optionList: [
          {'table_name': '商品期初库存','table_id': 'goods_opening_balance'},
          {'table_name': '组装单','table_id': 'assembly_order'},
          {'table_name': '组装单明细','table_id': 'assembly_order_details'},
          {'table_name': '拆装单','table_id': 'disassembly_order'},
          {'table_name': '拆装单明细','table_id': 'disassembly_order_details'},
          {'table_name': '调拨单','table_id': 'transfer_order'},
          {'table_name': '调拨单明细','table_id': 'transfer_order_details'},
        ],optionName: 'table_name',optionId: 'table_id'},
      {field_id: 'product_code',type: 'text',field_name: '商品编码'},
    ],

    //提交搜索数据
    searchObj: {
      date_s: first,  //开始日期
      date_e: last, //结束日期
      good_list: '',  //商品列表
      is_nothappen_notshow: false, //无发生额不显示
      quote_Warehouse: '',  //仓库
      table_id: '',  //业务类型
      product_code: ''
    },
    goodsList: [],  //商品列表

    displayField: [ //显示字段
      {field_id: 'goods_type_name',label: '商品类别',type: 'text'},
      {field_id: 'goods_model_name',label: '规格',type: 'text'},
      {field_id: 'order_date',label: '日期',type:'datetime',length: 'yyyy-MM-dd'},
    ],
    displayField2: [
      {field_id: 'order_no',label: '单据编号'},
      {field_id: 'table_name',label: '业务类型'},
      {field_id: 'customer_name',label: '往来单位'},
      {field_id: 'warehouse_name',label: '仓库'},
      {field_id: 'goods_unit_name',label: '单位'},
    ],
    subDisplayField: [  //明细显示字段
      {title: '结存',fields: [
          {field_id: 'balance_quantity',label: '单位数量'},
          {field_id: 'balance_unit_price',label: '单位成本'},
          {field_id: 'balance_price',label: '成本'},
        ], isAll: true},
      {title: '入库',fields: [
          {field_id: 'entry_quantity',label: '入库数量'},
          {field_id: 'entry_unit_price',label: '单位成本'},
          {field_id: 'entry_price',label: '成本'},
        ]},
      {title: '出库',fields: [
          {field_id: 'deliver_quantity',label: '出库数量'},
          {field_id: 'deliver_unit_price',label: '单位成本'},
          {field_id: 'deliver_price',label: '成本'},
        ]},
    ],
    //合计
    sumList: [],
  },
  //展开收起仓库
  toggleShow(e){
    let index = e.currentTarget.dataset.index;
    this.setData({[`list[${index}].isOpen`]: !this.data.list[index].isOpen})
  },
  //无发生额不显示
  onRadioChange(e){
    this.data.list = [];
    this.data.page = 1;
    this.setData({
      ['searchObj.is_nothappen_notshow']: e.detail,
    });
    this.getFirstPage();
  },
  //跳转页面
  navTo(e){
    let {tableid,rid} = e.currentTarget.dataset,
      url = '/DIYPages/general_entity/general_entity?entity=' + tableid;
    if (!tableid)return;
    /*if (['assembly_order','disassembly_order','transfer_order'].includes(tableid)) {
      wx.$toast('小程序不支持跳转到该模块！');
      return
    }*/
    if (['goods_opening_balance','assembly_order','disassembly_order','transfer_order'].includes(tableid)) {
      url = `/stock/stock_custom_list/stock_custom_list?status=edit&entity=${tableid}&rid=${rid}`
    }else {
      let where = [{
          CompareWith: tableid + '.row_id',
          Operator: "=",
          CompareValue: rid,
        }];
      wx.setStorageSync('echarts',where) ;
    }
    wx.navigateTo({
      url: url
    })
  },

  //搜索数据
  searchData(e){
    let {detail} = e,
      {goodsList,searchObj} = this.data;
    let good_list = [],
      quote_Warehouse = [];

    //输入框搜商品
    if (detail.iptVal){
      wx.$each(goodsList,(i,item)=>{
        if (item.goods_id.indexOf(detail.iptVal) >= 0 || item.goods_name.indexOf(detail.iptVal) >= 0){
          good_list.push(item.row_id);
        }
      });
    }
    //快速查询
    wx.$each(detail.quick,(i,item)=>{
      let key = item.CompareWith;
      if (key === 'date'){
        if (item.Operator === '>='){ key = 'date_s'; }
        if (item.Operator === '<=') { key = 'date_e'; }
      }
      searchObj[key] = item.CompareValue;
    });

    searchObj.good_list = good_list.join(',');

    this.setData({searchObj});
    this.getFirstPage();

  },

  //合计数据
  sumData(count){
    let {sumList,list} = this.data,
      key = ['balance_quantity','balance_price'],
      sum = [0,0];
    wx.$each(list,(i,item)=>{
      sum[0] = parseFloat(sum[0] + item[key[0]]);
      sum[1] = parseFloat((sum[1] + item[key[1]]).toFixed(2));
    });
    sumList = [
      {name: '记录数',num: count || 0},
      {name: '数量',num: sum[0]},
      {name: '成本',num: sum[1]}
    ];
    this.setData({sumList});
  },

  getDataList(){
    let {searchObj,page,limit,list} = this.data,
      post = {...searchObj, page, limit};
    wx.$post(1,'Stock/query_goods_inout_details_total',post).then(res=>{
      if (res.errcode != 0)return;
      let data = res.data.row;

      let total = 0,
        obj = {};

      if (data){
        if(page !== 1) data = [ ...list,...data ];
        total = res.data.total;
        obj = {total,list: data,page};
      }
      this.setData(obj);
      this.sumData(total);
    })
  },



  //获取下拉选项
  getOptionsList(arg){
    let [key,v,url,post,iseach,parse] = arg;
    return new Promise((resolve,reject) => {
      wx.$post(v, url, post).then(res=>{
        if (res.errcode != 0){
          reject();
          return;
        }
        let data = res.data.row || [],
          list = data;
        if (iseach){
          list = this.eachData(data,'row_id',parse);
        }
        resolve({[key]: list});
      });
    });
  },
  ready(){
    let parmaArr = [
        ['good_list',3,'DynamicQuery/query_dynamic_v1',{"oby": "goods.row_id desc","table_id": "goods","page":1,"limit":0}],  //商品
        ['quote_Warehouse',3,'DynamicQuery/query_dynamic_v1',{"oby": "Warehouse.row_id desc","table_id": "Warehouse","page":1,"limit":0}],  //仓库
        ['table_id',1,'Stock/query_stock_entity',{"row_id":0}],  //业务
      ];
    this.getOptionsList(parmaArr[0]).then(res=>{
      this.data.goodsList = res.good_list;
    });
    Promise.all([this.getOptionsList(parmaArr[1]),this.getOptionsList(parmaArr[2])]).then(res=>{
      let resObj = {};
      wx.$each(res,(i,item)=>{
        resObj = {...resObj,...item}
      });
      let searchList = this.data.searchList;
      wx.$each(searchList,(i,item)=>{
        if (resObj[item.field_id]){
          item.optionList = [...item.optionList,...resObj[item.field_id]];
        }
      });

      this.setData({
        searchList,
      });
    });
    this.getOptionsList(parmaArr[1]).then(res=>{
      this.setData({ [`searchList[1].optionList`]: res.quote_Warehouse });
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    let {date_s,date_e,good_list,quote_Warehouse} = options,
      {searchObj} = this.data;
    wx.$each({date_s,date_e,good_list,quote_Warehouse},(key,val)=>{
      if (val)searchObj[key] = val;
    })
    this.setData({searchObj});
    this.getDataList();
    this.ready();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
